const Classify = require("../../model/classify.model");

// 生成树形结构
function buildTree(arr, parentId = null) {
  const tree = [];
  for (const item of arr) {
    if (item.parent_id === parentId) {
      const children = buildTree(arr, item.id);
      let parentData = {parentTitle:null};
      if (children.length > 0) {
        item.children = children;
        item.children.forEach(parentData => {
          parentData.parentTitle = item.title;
      });
      }

      tree.push(item);
    }
  }
  return tree;
}
class ClassifyService {
  // async  getClassify(args) {
  //   const { current = 1, pageSize = 10, ...remainingParameters } = args;
  //   const offset = (current - 1) * pageSize;
  //   const { rows: list, count: total } = await Classify.findAndCountAll({
  //     limit: Number(pageSize),
  //     offset: offset,
  //     where: {
  //       ...remainingParameters,
  //     },
  //     order: [["title"]],
  //   });
  //   return {
  //     current,
  //     pageSize,
  //     total,
  //     list,
  //   };
  async getClassify(args) {
    const { current = 1, pageSize = 10, ...remainingParameters } = args;
    const { rows } = await Classify.findAndCountAll({
      where: {
        ...remainingParameters,
      },
      order: [["title"]],
    });
    const list = buildTree(JSON.parse(JSON.stringify(rows)));
    return {
      list,
    };
  }
  async addClassify(args) {
    const { id, createdAt, is_it_enabled, updatedAt, ...remainingParameters } =
      args;
    const res = await Classify.create(remainingParameters);
    return res;
  }
  async updateClassify(args) {
    const { id, createdAt, updatedAt, ...remainingParameters } = args;
    const resource = await Classify.update(
      {
        ...remainingParameters,
      },
      {
        where: {
          id,
        },
      }
    );
    return resource;
  }
  async deleteClassify(args) {
    const { id } = args;
    const res = await Classify.destroy({
      where: {
        id,
      },
    });
    return res;
  }
}

module.exports = new ClassifyService();
